package fr.lelouet.ga.examples.travelingSalesman;

import java.util.Random;
import java.util.Set;

import fr.lelouet.ga.Mutator;
import fr.lelouet.ga.utils.SetUtils;

public class TravelMutator implements Mutator<Travel> {

    static Random ran = new Random();

    public static Travel muteOneTown(Travel t) {
	Travel ret = (Travel) t.clone();
	if (ret.size() == 0 || ret.getMap().size() == 2) {
	    return ret;
	}
	int postToMute = TravelMutator.ran.nextInt(ret.size());
	Integer oldVal = ret.get(postToMute);
	Integer newVal = oldVal;
	while (newVal == oldVal) {
	    newVal = SetUtils.getAny(t.getMap().sociableTowns());
	}
	ret.set(postToMute, newVal);
	return ret;
    }

    protected int nbMaxElements;

    /**
     * 
     * @param maxelems
     *            number of elements we want the mutator to add.
     */
    public TravelMutator(int maxelems) {
	nbMaxElements = maxelems;
    }

    @Override
    public void mute(Set<Travel> set) {
	while (set.size() < nbMaxElements) {
	    Travel t = SetUtils.getAny(set);
	    set.add(TravelMutator.muteOneTown(t));
	}
    }
}
